/*
 * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.registry.custom.dia.ui.utils;

import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.custom.dia.ui.beans.EndpointBean;
import org.wso2.carbon.registry.common.ui.UIException;
import org.wso2.carbon.registry.resource.ui.clients.CustomUIServiceClient;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpSession;
import org.wso2.carbon.registry.custom.dia.ui.beans.xsd.AssociationBean;
import org.wso2.carbon.registry.custom.dia.ui.beans.xsd.TagBean;
import org.wso2.carbon.registry.custom.dia.ui.beans.xsd.ResourceTreeEntryBean;
import org.wso2.carbon.registry.custom.dia.ui.clients.TopicServiceClient; 
 
public class GetDocumentUtil {

    private static final Log log = LogFactory.getLog(GetDocumentUtil.class);
 
    private TopicServiceClient client;
    
    public GetDocumentUtil(ServletConfig config, HttpSession session) throws UIException {
        try {
            client = new TopicServiceClient(config, session);
        } catch (RegistryException e) {
             String msg = "Failed retrieve documentation details. " + e.getMessage();
            log.error(msg, e);
            throw new UIException(msg, e);
        }
    }

    public EndpointBean getEndpointBean(
            String path, ServletConfig config, HttpSession session) throws UIException {
//TODO change onclick submission of form to action in form tag
        try {
            CustomUIServiceClient customUIServiceClient =
                    new CustomUIServiceClient(config, session);

            String content = customUIServiceClient.getTextContent(path);
            OMElement document = AXIOMUtil.stringToOM(content);

            /*Structure of the OM
             *
             * <document>
                  <title>xxx</title>
                  <summary>xxxx</summary>
                  <externalLink>http://xxx</externalLink>
                  <relatedProduct>
                    <name>xxx</name>
                    <release>x.x.x</release>
                  </relatedProduct>
                  <environment>
                    <carbonPlatform>x.x.x</carbonPlatform>
                    <jdk>x.x</jdk>
                  </environment>
             * </document>
             */
            EndpointBean documentBean = new EndpointBean();
            Iterator i = document.getChildElements();
            while(i.hasNext()){
                OMElement ome = (OMElement) i.next();
                        //ome- child OMElements of document
                String localName = ome.getLocalName(); //ex: title, tags
                processLocalName(documentBean, localName, ome );
            }
 
            return documentBean; 
        } catch (Exception e) {
            String msg = "Failed to get end point details. " + e.getMessage();
            log.error(msg, e);
            throw new UIException(msg, e);
        }
    }

    private void processLocalName(EndpointBean documentBean, String localName, OMElement ome) {
        if(localName.equals("title")){
            documentBean.setTitle(ome.getText());
        }else if(localName.equals("summary")){
            documentBean.setSummary(ome.getText());
        }else if(localName.equals("externalLink")){
           documentBean.setExternalLink(ome.getText());
        }else if(localName.equals("relatedProduct")){
            Iterator i = ome.getChildElements();
            while(i.hasNext()){
                OMElement omeChild = (OMElement) i.next(); 
                String localNameChild = omeChild.getLocalName(); //ex: title, tags
                if(localNameChild.equals("product")){
                    documentBean.setProductName(omeChild.getText());
                } else if(localNameChild.equals("release")){
                    documentBean.setProductRelease(omeChild.getText());
                }
            }
        }else if(localName.equals("environment")){
            Iterator i = ome.getChildElements();
            while(i.hasNext()){
                OMElement omeChild = (OMElement) i.next();
                String localNameChild = omeChild.getLocalName(); //ex: title, tags
                if(localNameChild.equals("carbonPlatform")){
                    documentBean.setCarbonPlatform(omeChild.getText());
                } else if(localNameChild.equals("jdk")){
                    documentBean.setJdkPlatform(omeChild.getText());
                }
            }
        }
    }

    public AssociationBean[] getAllAssociations(String sPath){ 
        return client.getAllAssociations(sPath);
    }
//TODO remove this
    public TagBean[] getTagsString(
            String path, ServletConfig config, HttpSession session) throws UIException { 
 
           //     TopicServiceClient client = new TopicServiceClient(config, session);
                TagBean[] tagBeans = client.getTags(path);
                return tagBeans;
 
    }

    public ResourceTreeEntryBean getResourceTreeEntry(String resourcePath,
            ServletConfig config, HttpSession session) throws UIException{
        return client.getResourceTreeEntry(resourcePath);
    }

}

